package com.situ.meetingRoom.filter;

import com.situ.meetingRoom.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//登录过滤器
//登录时放行
//未登录时拦截跳转到登陆界面
@WebFilter(urlPatterns = "*.jsp")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        //判断用户是否登录
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //如果是登陆页面则直接放行
        if (request.getRequestURI().endsWith("login.jsp")){
             filterChain.doFilter(servletRequest, servletResponse);
             return;//后面的代码就不需要执行了
        }
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (user == null) {
            //没登陆，跳转登录页面
            response.sendRedirect(request.getContextPath()+"/user/login.jsp");
        } else {
            //登陆了 放行
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

}
